package models;

import com.avaje.ebean.Ebean;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import utils.ContainGame;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "userwishgame")
public class UserWishGame extends Model implements ContainGame {

    @EmbeddedId
    public UserWishGameKeys id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_email", insertable = false, updatable = false)
    public User account;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "game_id", insertable = false, updatable = false)
    public Game game;

    @Embeddable
    public static class UserWishGameKeys implements Serializable {

        public String account_email;
        public long game_id;

        public UserWishGameKeys(String idAccount, long idGame) {
            this.account_email = idAccount;
            this.game_id = idGame;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            UserWishGameKeys other = (UserWishGameKeys) obj;
            if ((this.account_email == null) ? (other.account_email != null) : !this.account_email.equals(other.account_email))
                return false;
            if (this.game_id != other.game_id)
                return false;
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 3;
            hash = 89 * hash + (this.account_email != null ?
                    this.account_email.hashCode() : 0);
            hash = 89 * hash + (int)this.game_id;
            return hash;
        }
    }

    public short priority;

    @Constraints.Required
    @Temporal(TemporalType.DATE)
    public Date dateadded;

    public UserWishGame(UserWishGameKeys id, short priority) {
        this.id = id;
        dateadded = new Date();
        this.priority = priority;
    }

    // -- Queries

    public static Model.Finder<UserWishGameKeys,UserWishGame> find = new Model.Finder(UserWishGameKeys.class, UserWishGame.class);

    public static List<UserWishGame> findAll() {
        return find.all();
    }

    @Override
    public Game getGame() {
        return game;
    }

    public static List<UserWishGame> findUserGames(String email) {
        return find.where().eq("account.email", email).orderBy("game.gametitle").findList();
    }

    public static UserWishGame findById(UserWishGameKeys id) {
        return find.where().eq("id", id).findUnique();
    }

    public static void removeWishGame(String email, long game) {
        Ebean.createSqlUpdate(
                "delete from userwishgame where account_email = :email and game_id = :game"
        ).setParameter("game", game)
         .setParameter("email", email).execute();
    }

    // --
}
